package com.iuie.ns.datum.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.iuie.ns.datum.mapper.BlogMapper;
import com.iuie.ns.datum.mapper.BookMapper;
import com.iuie.ns.datum.service.IBookInfoService;
import com.iuie.ns.datum.service.IFileService;
import com.iuie.ns.datum.vo.BookInfoVO;
import com.iuie.ns.frame.utils.ShiroUtils;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.web.dataset.vo.Page;
import com.iuie.ns.system.vo.user.SysUserVO;

@Service
public class BookInfoServiceImpl implements IBookInfoService{

	@Autowired
	private BookMapper bookMapper;
	
	@Autowired
	private IFileService fileService;
	
	@Autowired
	private BlogMapper blogMapper;
	
	@Override
	public List<BookInfoVO> findAll() {
		return bookMapper.findAll();
	}

	@Override
	public List<BookInfoVO> queryList(Page page, BookInfoVO bookInfoVO) {
		List<BookInfoVO> bookInfoVOs = null;
		if (page == null) {
			bookInfoVOs = findAll();
			fillBlogInfo(bookInfoVOs);
			return findAll();
		}
		PageHelper.startPage(page.getPage(), page.getRows(), true);
		bookInfoVOs = bookMapper.queryList(page,bookInfoVO);
		fillBlogInfo(bookInfoVOs);
		page.loadData(bookInfoVOs);
		return bookInfoVOs;
	}

	private void fillBlogInfo(List<BookInfoVO> bookInfoVOs) {
		for(BookInfoVO bookInfoVO : bookInfoVOs){
			String bookId = bookInfoVO.getBookId();
			bookInfoVO.setBlogInfoVOList(blogMapper.findBlogByBookId(bookId));
		}
	}

	@Override
	public BookInfoVO saveOne(BookInfoVO bookInfoVO) throws Exception {
		SysUserVO user = (SysUserVO) ShiroUtils.getCurrentUser();
		String userName = user.getUserName();
		String userId = user.getUserId();
		bookInfoVO.setBookId(StringUtils.uuid());
		bookInfoVO.setEntryDateTime(new Date());
		bookInfoVO.setUserName(userName);
		bookInfoVO.setUserId(userId);
		bookMapper.save(bookInfoVO);
		return bookInfoVO;
	}

	@Override
	public BookInfoVO findBookById(String bookId) {
		return bookMapper.findBookById(bookId);
	}

	@Override
	public void deleteBook(String bookId) {
		 BookInfoVO bookInfo = findBookById(bookId);
		 Long bookFileId = bookInfo.getUrlFileId();
		 Long coverFileId = bookInfo.getCoverFileId();
		 if(bookFileId != null){
			 fileService.deleteFileById(bookFileId, true);
		 }
		 if(coverFileId != null){
			 fileService.deleteFileById(coverFileId, true);
		 }
		 bookMapper.deleteBookById(bookId);	
	}

	@Override
	public void updateBook(BookInfoVO bookInfo) {
		bookMapper.update(bookInfo);
	}

}
